package com.prince.web.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import com.prince.web.base.BaseService;
import com.prince.web.service.ConfigService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.prince.bean.CommonWebResponse;
import com.prince.bean.ResultParams;
import com.prince.bean.WebCode;
import com.prince.constant.Constants;
import com.prince.mapper.ConfigMapper;
import com.prince.model.Config;
import com.prince.model.ConfigExample;
import com.prince.model.ConfigExample.Criteria;
import com.prince.page.Page;
import com.prince.util.DateUtil;
import com.prince.util.JsonUtil;
import com.prince.util.MapUtil;
import com.prince.util.StringUtil;

@Service
public class ConfigServiceImpl extends BaseService implements ConfigService {

	@Resource
	private ConfigMapper configMapper;

	@Override
	public Map<String, Object> findConfigByPage(Map<String, Object> paramMap, Page page) {
		ResultParams response = CommonWebResponse.getSuccessResponseCodeMsgParams();
          //判断参数是否为空
		if (null == paramMap || paramMap.size() == 0) {
			logger.debug("[ConfigServiceImpl] findConfigByPage param beanJson is null");
			return CommonWebResponse.getCommonRespCodeMsgParams(WebCode.systemError).toHashMap();
		}

         //添加查询条件
		ConfigExample configExample = new ConfigExample();
		Criteria criteria = configExample.createCriteria();
		if (MapUtil.isNotEmpty(paramMap, "title")) {
			// criteria.andTitleEqualTo(paramMap.get("title").toString());
		}
		if (MapUtil.isNotEmpty(paramMap, "startTime") && MapUtil.isNotEmpty(paramMap, "endTime")) {
			Date startTime = DateUtil.strToYYYYMMDD(paramMap.get("startTime").toString());
			Date endTime = DateUtil.strToYYYYMMDD(paramMap.get("endTime").toString());
			criteria.andCreatedGreaterThan(startTime);
			criteria.andCreatedLessThanOrEqualTo(endTime);
		}
		// 封装参数
		paramMap.remove("startTime");
		paramMap.remove("page");

		paramMap.remove("endTime");

		paramMap.remove("rows");
		paramMap.put("del", Constants.YES);
		//反射封装参数
		StringUtil.reflectMap(criteria, paramMap);
		int total = configMapper.countByExample(configExample);
        logger.debug("[ConfigServiceImpl] findConfigByPage 总记录数"+total);
        if (null != page) {
        	configExample.setPage(page);
		}
		configExample.setOrderByClause("created desc");
		List<Config> list = configMapper.selectByExample(configExample);
		logger.debug("[ConfigServiceImpl] findConfigByPage 返回结果"+JsonUtil.toJSONString(list));
		return response.toHashMapByPage(total, list);
	}

	@Override
	public Map<String, Object> addConfig(Config config) {
		ResultParams response = CommonWebResponse.getSuccessResponseCodeMsgParams();
		config.setCreated(new Date());
		config.setDel(Constants.YES);
		logger.debug("[ConfigServiceImpl] addConfig 参数是"+JsonUtil.toJSONString(config));
		int i = configMapper.insertSelective(config);
		if (!(i > 0)) {
			logger.debug("[addConfig] insert Config is fail. Config={}", JSON.toJSONString(config));
			return CommonWebResponse.getCommonRespCodeMsgParams(WebCode.systemError).toHashMap();
		}
		//清空缓存
//		configCache.del();
		return response.toHashMap();
	}

	@Override
	public Map<String, Object> delConfig(Config config) {
		ResultParams response = CommonWebResponse.getSuccessResponseCodeMsgParams();
		//逻辑删除
		config.setDel(Constants.NO);
		logger.debug("[ConfigServiceImpl] delConfig 参数是"+JsonUtil.toJSONString(config));
		int i = configMapper.updateByPrimaryKeySelective(config);
		if (!(i > 0)) {
			logger.debug("[delConfig] del Config is fail id={}", config.getId());
			return CommonWebResponse.getCommonRespCodeMsgParams(WebCode.systemError).toHashMap();
		}
		//清空缓存
//		configCache.del();
		return response.toHashMap();
	}

	@Override
	public Map<String, Object> updateConfig(Config config) {
		ResultParams response = CommonWebResponse.getSuccessResponseCodeMsgParams();
        logger.debug("[ConfigServiceImpl] updateConfig 参数"+JsonUtil.toJSONString(config));
		int i = configMapper.updateByPrimaryKeySelective(config);
		if (!(i > 0)) {
			logger.debug("[delConfig] update Config is fail id={}", config.getId());
			return CommonWebResponse.getCommonRespCodeMsgParams(WebCode.systemError).toHashMap();
		}
		//清空缓存
//		configCache.del();
		return response.toHashMap();
	}

	@Override
	public Map<String, Object> findConfigByCondition(Config config) {
		ResultParams response = CommonWebResponse.getSuccessResponseCodeMsgParams();
        //创建查询并添加条件id
		ConfigExample configExample = new ConfigExample();
		Criteria criteria = configExample.createCriteria();
		if (null != config.getId()) {
			criteria.andIdEqualTo(config.getId());
		}
		if(null != config.getName()) {
			criteria.andNameEqualTo(config.getName());
		}
		List<Config> list = configMapper.selectByExample(configExample);
        //判断是否为空
		if (null == list || list.size() == 0) {
			logger.debug("[findConfigByCondition] find ConfigList is null");
			return CommonWebResponse.getCommonRespCodeMsgParams(WebCode.systemError).toHashMap();
		}
		logger.debug("[ConfigServiceImpl] findConfigByCondition 返回结果为"+JsonUtil.toJSONString(list));
		response.put("list", list);
		return response.toHashMap();
	}

	@Override
	public Map<String, Object> dqueryConfig(Config config) {
		ResultParams response = CommonWebResponse.getSuccessResponseCodeMsgParams();
        //创建criteria
		ConfigExample configExample = new ConfigExample();
		Criteria criteria = configExample.createCriteria();
		// 模糊查询条条件 number,name
		if (StringUtil.isNotEmpty(config.getName())) {

			criteria.andNameLike("%" + config.getName() + "%");

		}
		if (StringUtil.isNotEmpty(config.getValue())) {

			criteria.andValueLike("%" + config.getValue() + "%");

		}
		if (StringUtil.isNotEmpty(config.getDescribed())) {

			criteria.andDescribedLike("%" + config.getDescribed() + "%");

		}
        //分页参数
		Page page = new Page();
		page.setBegin(0);
		page.setLength(10);
		configExample.setPage(page);
		logger.debug("[ConfigServiceImpl] dqueryConfig 参数"+JsonUtil.toJSONString(config));
		List<Config> list = configMapper.selectByExample(configExample);
       //判断是否为空
		if (null == list || list.size() == 0) {
			logger.debug("[findConfigByCondition] find ConfigList is null");
			return CommonWebResponse.getCommonRespCodeMsgParams(WebCode.systemError).toHashMap();
		}
		logger.debug("[ConfigServiceImpl] dqueryConfig 返回结果"+JsonUtil.toJSONString(list));
		response.put("list", list);
		return response.toHashMap();
	}

	/*
	 * 查询数据库中的数据放入缓存
	 * 
	 */
	@Override
	public Map<String, Object> findConfigListAndMap() {
		ResultParams response = CommonWebResponse.getSuccessResponseCodeMsgParams();
          //获取缓存
//		String configValue = configCache.get();
		String configValue = null;
		//判断值是否为空，如果是空，查询所有把值放入缓存中
		if (StringUtil.isEmpty(configValue)) {
			// Map<String, Object> map = getconfigMap();
			Map<String, Object> map = new HashMap<String, Object>();
			ConfigExample configExample = new ConfigExample();

			Criteria criteria = configExample.createCriteria();

			criteria.andStatusEqualTo("yes");
			List<Config> configs = configMapper.selectByExample(configExample);
			if (configs != null && configs.size() > 0) {
				for (Config config : configs) {

					map.put(config.getName(), config.getValue());
				}
			}
			configValue = JSON.toJSONString(map);
			if (!StringUtil.isEmpty(configValue)) {
				logger.info(map.toString());
//				configCache.set(JSON.toJSONString(map));
			}
		}
		// System.out.println(map.get("001").get("config").toString());
		response.put("data", configValue);
		return response.toHashMap();
	}

	/*
	 * 查询数据库中的数据放入缓存
	 * 
	 */
	@Override
	public Map<String, Object> getConfigMap() {
		//获取缓存
//		String configValue = configCache.get();
		String configValue = null;
		//判断值是否为空，如果是空，查询所有把值放入缓存中
		if (StringUtil.isEmpty(configValue)) {
			// Map<String, Object> map = getconfigMap();
			Map<String, Object> map = new HashMap<String, Object>();
			ConfigExample configExample = new ConfigExample();

			Criteria criteria = configExample.createCriteria();

			criteria.andStatusEqualTo(Constants.YES);
			List<Config> configs = configMapper.selectByExample(configExample);

			if (configs != null && configs.size() > 0) {
				for (Config config : configs) {
					map.put(config.getName(), config.getValue());
				}
			}
			configValue = JSON.toJSONString(map);
			if (!StringUtil.isEmpty(configValue)) {
				logger.info(map.toString());
//				configCache.set(JSON.toJSONString(map));
			}
			return map;
		}

		return JsonUtil.JSONToHashMap(configValue);
	}

	@Override
	public Config findConfigName(String name) {
		//根据名称查询
		ConfigExample configExample = new ConfigExample();
		Criteria criteria = configExample.createCriteria();
		criteria.andDelEqualTo(Constants.YES);
		criteria.andStatusEqualTo(Constants.YES);
		if (StringUtil.isNotEmpty(name)) {
			criteria.andNameEqualTo(name);
		}
		List<Config> list = configMapper.selectByExample(configExample);
		logger.info("[ConfigServiceImpl] findConfigName 常量表查询结果={}", name + ":" + JsonUtil.toJSONString(list));
		return null == list || list.size() == 0 ? null : list.get(0);
	}

	@Override
	public Map<String, Object> getConfigBywechat() {
		ResultParams response = CommonWebResponse.getSuccessResponseCodeMsgParams();
		ConfigExample configExample = new ConfigExample();
		Criteria criteria = configExample.createCriteria();
        //添加名称条件
		criteria.andNameEqualTo("brandUrl");
		List<Config> list = configMapper.selectByExample(configExample);
		logger.debug("[ConfigServiceImpl] getConfigBywechat 常量表查询结果"+JsonUtil.toJSONString(list));
		response.put("list", list);
		return response.toHashMap();
	}

	@Override
	public Map<String, Object> getConfigByName(String name) {
       //根据名称查询数据
		ResultParams response = CommonWebResponse.getSuccessResponseCodeMsgParams();
		ConfigExample configExample = new ConfigExample();
		Criteria criteria = configExample.createCriteria();
		criteria.andNameEqualTo(name);
		List<Config> list = configMapper.selectByExample(configExample);
		logger.debug("[ConfigServiceImpl] getConfigByName 返回结果"+JsonUtil.toJSONString(list));
		response.put("list", list);
		return response.toHashMap();
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Config> getConfigMapByType(String type, @SuppressWarnings("rawtypes") Map map) {
        //创建查询
		ConfigExample configExample = new ConfigExample();
		Criteria criteria = configExample.createCriteria();
         //添加查询条件
		criteria.andTypeEqualTo(type);
		criteria.andStatusEqualTo(Constants.YES);
		criteria.andDelEqualTo(Constants.YES);
		List<Config> list = configMapper.selectByExample(configExample);
		logger.info("[ConfigServiceImpl] getConfigMapByType 请求参数={}", type + ",请求结果=" + list);
		// 将查询到的结果封装到Map里面
		if (MapUtil.isNotEmpty(map)) {

			for (Config config : list) {
				map.put(config.getName(), config.getValue());
			}
		}

		return list;
	}


	@Override
	public Map<String, Object> findConfigByType(String type) {
		ResultParams response = CommonWebResponse.getSuccessResponseCodeMsgParams();
		ConfigExample configExample=new ConfigExample();
		Criteria criteria = configExample.createCriteria();
		criteria.andTypeEqualTo(type);
		//criteria.andStatusEqualTo(Constants.YES);
		criteria.andDelEqualTo(Constants.YES);
		configExample.setGroupBy("created desc");
		List<Config> list = configMapper.selectByExample(configExample);
        for (Config config : list) {
			config.setRemark(config.getName());
		}
		response.put("list", list);
		return response.toHashMap();
	}
	/**
	 * 通过key查询
	 * @param name
	 * @return
	 */
	@Override
	public String findConfigByKey(String name,String defaultValue) {
		Config configName = this.findConfigName(name);
		return null != configName ? configName.getValue() : defaultValue;
	}
}
